//
//  DCImageCache.m
//  DCWebImage
//
//  Created by Joinwe on 16/6/1.
//  Copyright © 2016年 Joinwe. All rights reserved.
//

#import "DCImageCache.h"

@implementation DCImageCache

static DCImageCache *imageCache = nil;

//单例类
+(DCImageCache *)sharedImageCache{
    //上锁
    @synchronized (self) {
        if (imageCache == nil) {
            imageCache = [[DCImageCache alloc] init];
        }
    }
    return imageCache;
}

+ (id)alloc{
    @synchronized (self) {
        if (imageCache == nil) {
            imageCache = [super alloc];
        }
    }
    return imageCache;
}

- (id)init{
    self = [super init];
    if (self) {
        _allCache = [[NSMutableDictionary alloc] init];
        
        //当系统发出内存警告的时候自动清除内存
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clearMemory) name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
    }
    
    return self;
}

//清除内存
- (void)clearMemory{
    NSLog(@"清除内存中缓存的图片");
    [_allCache removeAllObjects];
}


- (UIImage *)seachImageFromMemoryWithURLString:(NSString *)urlString{
    //从内存（字典）中找图片
    //假设在字典中  图片地址是键  UIImage对象是值
    return [_allCache objectForKey:urlString];
}

//获取内存大小
- (long long)getMemorySize{
    long long size = 0;
    for (NSString *key in _allCache.allKeys) {
        UIImage *image = [_allCache objectForKey:key];
        NSData *data = UIImageJPEGRepresentation(image, 1);
        size += data.length;
    }
    return size;
}

//清除图片所占的存储
- (void)clearDisk{
    //图片缓存的位置
    NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/DCImageCache"];
    [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
}


- (UIImage *)searchImageFromSandBoxWithURLString:(NSString *)urlString{
    //我们默认的沙盒存储路径为 ~/Documents/DCImageCache/图片的地址为文件名
    NSString *path = [self getPathWithFileName:urlString];
    UIImage *image = [UIImage imageWithContentsOfFile:path];
    if (image) {
        //缓存到内存
        [_allCache setObject:image forKey:urlString];
        NSLog(@"内存中的图片 _allCache    %@", _allCache);
    }
    return image;
}

//根据文件名获取文件的路径
- (NSString *)getPathWithFileName:(NSString *)fName{
    NSString *dPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/DCImageCache"];
    if (![[NSFileManager defaultManager] fileExistsAtPath:dPath]) {
        [[NSFileManager defaultManager] createDirectoryAtPath:dPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    NSString *name = [[fName componentsSeparatedByString:@"/"] lastObject];
    NSString *fPath = [NSString stringWithFormat:@"%@/%@",dPath,name];
    NSLog(@"fPath %@", fPath);
    return fPath;
}


- (void)downloadImageWithURLString:(NSString *)urlString completionBlock:(void (^)(UIImage *))block{
    //使用GCD来下载图片，先获取全局队列
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    //异步操作
    dispatch_async(queue, ^{
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
        UIImage *image = [UIImage imageWithData:data];
        
        //回到主队列进行操作
        dispatch_async(dispatch_get_main_queue(), ^{
            block(image);
            
            if (image != nil) {
                //缓存到内存
                [_allCache setObject:image forKey:urlString];
                
                NSLog(@"内存中的图片 _allCache    %@", _allCache);
                
                
                //缓存到沙盒
                BOOL isSuccess = [data writeToFile:[self getPathWithFileName:urlString] atomically:YES];
                
                NSLog(@"缓存到沙盒 isSuccess  %d",isSuccess);
            }
        });
    });

}

@end
